package com.lqq.chapter05;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author lqq677
 * @Date 2021/8/11 15:43
 * @Description 可重入锁：Lock，必须自己手动上锁和释放锁
 */
public class RLock {
    public static void main(String[] args) {

        Lock lock = new ReentrantLock();//可重入锁

        new Thread(() ->{//线程A

             try {
                 lock.lock();//外层上锁
                 System.out.println("外层...");

                      try {
                          lock.lock();//内存上锁
                          System.out.println("内层...");
                     }catch (Exception e){
                         e.printStackTrace();
                     }finally {
                         //lock.unlock();//line28 内层解锁
                     }

             }catch (Exception e){
                 e.printStackTrace();
             }finally {
                 lock.unlock();//外层解锁
             }

                }, "A").start();


        new Thread(() ->{//线程B
              try {
                  lock.lock();
                  System.out.println("线程B试图获取锁...");
             }catch (Exception e){
                 e.printStackTrace();
             }finally {
                 lock.unlock();
             }
                }, "B").start();

    }
}
